package com.rin.hdfs;

import com.rin.entity.Event;

import java.io.InputStream;
import java.util.Collections;

import com.rin.util.ParseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author RinMi
 * @since 2023/6/10
 */

@RestController
@RequestMapping("/hdfs")
public class HDFSController {

    @Resource
    private HDFSService hdfsService;

    @PostMapping("upload")
    public String upload(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            return hdfsService.uploadEntity(file.getInputStream(), filename);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @PostMapping("download")
    public List<Object> download(@RequestParam("serialLocation") String serialLocation) {
        try {
            return hdfsService.downloadEntity(serialLocation);
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    @PostMapping("delete")
    public void delete(@RequestParam("serialLocation") String serialLocation) {
        try {
            hdfsService.delete(serialLocation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("parseFile")
    public void parseFile(@RequestBody Event event) {
        try {
            hdfsService.upload(event, String.valueOf(event.getEventId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("parseEntity")
    public Object parseEntity(@RequestBody Event event) {
        try {
            String destination = "/" + event.getClass().getSimpleName() + "/" + event.getEventId();
            InputStream inputStream = hdfsService.download(destination);
            if (inputStream == null) {
                System.out.println("获取失败");
            }
            return ParseEntity.parseEntity(inputStream, event.getClass());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
